/*    file: CSecureDataStore.cpp
 *    desc:
 * 
 * created: 2017-08-01
 *  author: chuanjiang.zh@qq.com
 * company: 
 */

#include "CSecureDataStore.h"
#include "TStringUtil.h"

static bool toObject(sqlite3_stmt *stmt, std::string& value)
{
	int col = 0;
	value = (const char*)sqlite3_column_text(stmt, col++);
	return true;
}


CSecureDataStore::CSecureDataStore()
{

}

CSecureDataStore::~CSecureDataStore()
{
	close();
}

bool CSecureDataStore::open(const std::string& filepath)
{
	if (!m_sqlite.open(filepath))
	{
		return false;
	}

	createTables();
	return true;
}

void CSecureDataStore::close()
{
	m_sqlite.close();
}

bool CSecureDataStore::isOpen()
{
	return m_sqlite.isOpen();
}

bool CSecureDataStore::getValue(const std::string& key, std::string& value)
{
	std::string sql = comn::StringUtil::format("select `value` from KeyValue where id='%s'", key.c_str());
	return m_sqlite.queryString(sql, value);
}

bool CSecureDataStore::contains(const std::string& key)
{
	std::string value;
	return getValue(key, value);
}

bool CSecureDataStore::setValue(const std::string& key, const std::string& value)
{
	if (key.empty())
	{
		return false;
	}

	std::ostringstream oss;
	oss << "replace into KeyValue values(";
	oss << "'" << key << "'";
	oss << ",'" << value << "'";
	oss << ")";

	std::string sql = oss.str();
	return m_sqlite.execute(sql);
}

bool CSecureDataStore::removeValue(const std::string& key)
{
	std::string sql = comn::StringUtil::format("delete from KeyValue where id='%s'", key.c_str());
	return m_sqlite.execute(sql);
}

void CSecureDataStore::removeValues()
{
	std::string sql = "delete from KeyValue";
	m_sqlite.execute(sql);
}

int CSecureDataStore::getKeys(std::vector< std::string >& keys)
{
	std::string sql = "select id from KeyValue";
	return m_sqlite.queryObjects(sql, keys);
}

int CSecureDataStore::findKeys(const std::string& pattern, std::vector< std::string >& keys)
{
	std::string sql = comn::StringUtil::format("select id from KeyValue where `id` like '%%%s%%'", pattern.c_str());
	return m_sqlite.queryObjects(sql, keys);
}

bool CSecureDataStore::createTables()
{
	const char* sqlData =
		"CREATE TABLE IF NOT EXISTS `KeyValue` ("\
		"`id` VARCHAR(255) NOT NULL,"\
		"`value` VARCHAR(2048) NULL,"\
		"PRIMARY KEY (`id`))"\
		";";

	return m_sqlite.execute(sqlData);
}
